"""
自定义Jinja2模板过滤器
"""
import json
from datetime import datetime
from flask import Blueprint

def init_template_filters(app):
    """初始化自定义模板过滤器"""
    
    @app.template_filter('from_json')
    def from_json_filter(value):
        """将JSON字符串转换为Python对象"""
        if not value:
            return {}
        try:
            if isinstance(value, str):
                return json.loads(value)
            return value
        except (json.JSONDecodeError, TypeError):
            return {}
    
    @app.template_filter('get_time_value')
    def get_time_value_filter(data):
        """从trigger_args中提取时间值"""
        if not data:
            return ''
        
        if isinstance(data, str):
            try:
                data = json.loads(data)
            except json.JSONDecodeError:
                return ''
        
        if isinstance(data, dict):
            # 处理interval类型
            if 'hours' in data:
                return f"{data['hours']}小时"
            elif 'minutes' in data:
                return f"{data['minutes']}分钟"
            elif 'seconds' in data:
                return f"{data['seconds']}秒"
            elif 'days' in data:
                return f"{data['days']}天"
            elif 'weeks' in data:
                return f"{data['weeks']}周"
            
            # 处理cron类型
            elif 'hour' in data:
                return f"每天{data['hour']}点"
            elif 'day_of_week' in data:
                weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
                day = data['day_of_week']
                if isinstance(day, int) and 0 <= day <= 6:
                    return f"每{weekdays[day]}"
                return f"每{day}天"
            elif 'day' in data:
                return f"每月{data['day']}号"
            elif 'month' in data:
                months = ['', '一月', '二月', '三月', '四月', '五月', '六月', 
                         '七月', '八月', '九月', '十月', '十一月', '十二月']
                month = data['month']
                if isinstance(month, int) and 1 <= month <= 12:
                    return f"每{months[month]}"
                return f"每{month}月"
        
        return str(data)
    
    @app.template_filter('format_datetime')
    def format_datetime_filter(value, format='%Y-%m-%d %H:%M:%S'):
        """格式化日期时间"""
        if not value:
            return ''
        try:
            if isinstance(value, str):
                # 尝试解析ISO格式
                dt = datetime.fromisoformat(value.replace('Z', '+00:00'))
            elif isinstance(value, datetime):
                dt = value
            else:
                return str(value)
            
            return dt.strftime(format)
        except (ValueError, AttributeError):
            return str(value)
    
    @app.template_filter('task_status_text')
    def task_status_text_filter(enabled):
        """任务状态文本"""
        return "启用" if enabled else "禁用"
    
    @app.template_filter('task_status_class')
    def task_status_class_filter(enabled):
        """任务状态CSS类"""
        return "layui-bg-green" if enabled else "layui-bg-gray"
    
    @app.template_filter('trigger_type_text')
    def trigger_type_text_filter(trigger):
        """触发器类型文本"""
        trigger_texts = {
            'date': '一次性',
            'interval': '间隔调度',
            'cron': '定时调度'
        }
        return trigger_texts.get(trigger, trigger)
    
    @app.template_filter('safe_json')
    def safe_json_filter(value):
        """安全的JSON序列化"""
        if not value:
            return '{}'
        try:
            if isinstance(value, str):
                # 验证是否为有效JSON
                json.loads(value)
                return value
            else:
                return json.dumps(value, ensure_ascii=False)
        except (json.JSONDecodeError, TypeError):
            return '{}' 